package com.xq.tmall.agu.timer;

import com.xq.tmall.entity.Stock;
import com.xq.tmall.service.StockHistoryService;
import com.xq.tmall.service.StockService;
import com.xq.tmall.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class StockHistoryFetchBidTimer {

    @Autowired
    private StockHistoryService stockHistoryService;


    @Autowired
    private StockService stockService;

    /**
     * 每天9:30抓取竞价数据
     */
    @Scheduled(cron = "0 28 9 * * ?")
    public void fetch() {
        log.info("历史数据开始抓取竞价量数据...");
        try {
            LocalDateTime dateTime = LocalDateTime.now();
            // 周末不执行
            boolean isWeek = DateUtil.isWeekend(dateTime);
            if(isWeek){
                log.info("周末不执行");
                return;
            }
            // 获取所有股票信息
            List<Stock> stockList = stockService.findAllStockInfo();
            log.info("获取到 {} 只股票信息", stockList.size());

            // 批量插入历史记录
            if (!CollectionUtils.isEmpty(stockList)) {
                stockHistoryService.batchInsertBid(stockList);
                log.info("成功插入 {} 条历史股票数据", stockList.size());
            } else {
                log.warn("未获取到有效的股票信息");
            }
        }catch (Exception e){
            log.info("历史数据开始抓取竞价量数据失败");
        }
    }

    @Scheduled(cron = "0 40 16 * * ?")
    public void delete() {
        Date now = new Date();
        SimpleDateFormat sb = new SimpleDateFormat("yyyy-MM-dd");
        stockHistoryService.nowDelete(sb.format(now));
    }
}
